package com.niiwoo.civet.account.initialize;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dao.entity.AccountBase;
import com.niiwoo.civet.account.dao.entity.AccountBaseExample;
import com.niiwoo.civet.account.dao.mapper.AccountBaseMapperExt;
import com.niiwoo.civet.account.dao.mapper.AccountCompanyMapperExt;
import com.niiwoo.civet.account.initialize.org.OrgAccount;
import com.niiwoo.civet.base.constant.OrgConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 初始化系统常驻数据
 * JVM 缓存
 */
@Slf4j
@Component
public class InitializeJVMData implements InitializingBean {

    @Autowired
    private AccountBaseMapperExt accountBaseMapperExt;
    @Autowired
    private AccountCompanyMapperExt accountCompanyMapperExt;

    @Override
    public void afterPropertiesSet() throws Exception {
        initOrgNiWoTa();
    }

    /**
     * 初始化你我他的机构存管账号
     */
    private void initOrgNiWoTa(){
        AccountBaseExample example = new AccountBaseExample();
        AccountBaseExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdEqualTo(OrgConstant.NIWOTA_ORG_ID);
        criteria.andUserIdEqualTo(OrgConstant.NIWOTA_ORG_ID);
        List<AccountBase> accountBaseList = accountBaseMapperExt.selectByExample(example);
        if( accountBaseList.size() == 0 ){
            log.warn("你我他机构账户数据为空,初始化机构存管账号失效");
        }else if( accountBaseList.size() == 1 ){
            AccountBase accountBase = accountBaseList.get(0);
            OrgAccount orgAccount = new OrgAccount();
            orgAccount.setAccountNO(accountBase.getAccountNo());
            Singleton.getInstance().setOrgNiWoTa(orgAccount);
            log.info("初始化机构账户数据成功，缓存数据{}", JSON.toJSONString(orgAccount));
        }else {
            log.warn("你我他机构账户异常，请手工排查，不予初始化机构存管账号");
        }
    }
}
